<template>
  <div class="plugin-miravia">
    <div class="box auth" v-if="!ok">
      <img :src="plugin.img()">
      <div class="message">{{ plugin.t(loading ? 'auth.message.loading' : 'auth.message.error.auth') }}</div>
      <t-button theme="primary" :loading="loading" @click="onUrl">{{ plugin.t('auth.button') }}</t-button>
    </div>
    <div class="box" v-else>
      <div class="left-box" style="width: 270px">
        <div class="bar">
          <div class="title">{{ plugin.t('name') }}</div>
        </div>
        <t-menu class="menu" theme="light" :value="$route.path" @change="path => $router.push(path)" width="250px">
          <t-menu-item value="/plugin/miravia">
            <template #icon>
              <t-icon name="store" />
            </template>
            {{ plugin.t('tabs.0') }}
          </t-menu-item>
          <t-menu-item value="/plugin/miravia/order">
            <template #icon>
              <t-icon name="task" />
            </template>
            {{ plugin.t('tabs.1') }}
          </t-menu-item>
          <t-menu-item value="/plugin/miravia/reverse">
            <template #icon>
              <t-icon name="task-error" />
            </template>
            {{ plugin.t('tabs.2') }}
          </t-menu-item>
        </t-menu>
      </div>
      <router-view />
    </div>
  </div>
</template>
<script setup>
  import { ref } from 'vue'
  import { useRoute } from 'vue-router'
  import app from '@/app'
  import index from '../index'
  import miraviaStore from '../store'
  import { auth, url } from '@/api/provider/miravia'

  const plugin = index.plugin
  const route = useRoute()
  const loading = ref(false)
  const ok = miraviaStore.ok
  
  const onUrl = () => {
    loading.value = true
    url().then(u => {
      window.location.href = u + encodeURIComponent(window.location.href)
    })
  }

  const onMain = async () => {
    if(ok.value) return
    loading.value = true

    // 判断是否进行授权
    if(route.query.code) {
      try{
        await auth(route.query.code)
      } catch (e) {
        app.message('warning', e.message)
      }
    }

    // 判断是否授权成功
    miraviaStore.main().finally(() => loading.value = false)
  }

  onMain()
</script>
<style lang="scss">
  @import '@/style/global';

  .plugin-miravia{
    .menu{
      background: 0;
      .t-default-menu__inner .t-menu{
        padding: 0
      }
      .t-menu__item.t-is-active:not(.t-is-opened){
        background-color: var(--td-brand-color-2)
      }
    }

    .auth{
      height: 70vh;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center; 

      img{
        width: 100px;
        margin-bottom: 20px;
      }

      .message{
        font-size: 14px;
        color: $color-content;
        margin-bottom: 20px;
      }
    }
  }
</style>